package 滑动;

import java.util.HashMap;

public class _2461长度为K子数组中的最大和 {
    public static long maximumSubarraySum(int[] nums, int k) {
        long max = 0;
        long sum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            map.merge(nums[i], 1, Integer::sum);
            if (i < k - 1) {
                continue;
            }
            if (map.size() == k) {
                max = Math.max(max, sum);
            }
            int tail = nums[i - k + 1];
            sum -= tail;
            if (map.merge(tail, -1, Integer::sum) == 0) {
                map.remove(tail);
            }
        }
        return max;
    }
    public static void main(String[] args) {
        long maximumSubarraySum = maximumSubarraySum(new int[]{1,5,4,2,9,9,9}, 3);
        System.out.println(maximumSubarraySum);
    }
}
